<?php
namespace api\components;

use api\models\SmsSendLog;
use api\modules\app\models\ServiceProviderConfig;
use api\utils\LogUtil;

class Sms
{
    private $instance;

    public function __construct($account = '')
    {
        $provider = ServiceProviderConfig::findOne(['type' => 'sms', 'status' => 1, 'account' => $account]);
        if (empty($provider) && !empty($metaCode)) {
            // 默认配置
            $provider = ServiceProviderConfig::findOne(['type' => 'sms', 'account' => 0]);
        }
        if (empty($provider)) {
            LogUtil::warn('Component-Sms: no servicer provider config');
            return false;
        }
        $className = 'app\\Libs\\Sms\\' . ucfirst($provider->getName());
        if (class_exists($className)) {
            $params = json_decode($provider['params'], true);
            $params['secretId'] = $provider['secret_id'];
            $params['secretKey'] = $provider['secret_key'];
            $params['host'] = $provider['host'];
            $params['account'] = $account;
            $this->instance = (new $className())->getInstance($params);
            return true;
        }
        LogUtil::warn('Components-Sms: init sms instance fail. className: ' . $className);
        return false;
    }

    /**
     * 发送短信
     */
    public function sendSms($phones = [], $params = [])
    {
        if (empty($this->instance)) {
            LogUtil::warn('Components-Sms: no sms instance to send. userIds: ' . json_encode($phones));
            return false;
        }

        $response = $this->instance->sendSms($phones, $params);
        if (!empty($response['logs'])) {
            SmsSendLog::batchInsert(array_keys($response['logs'][0]), $response['logs']);
        }
        return $response['result'] ?? false;
    }
}
